package com.example.common.aspect;


import com.example.common.logmapper.LogMapper;


import com.example.common.utils.UserContext;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class LogASpect {
    @Autowired
    private LogMapper logMapper;
    @Pointcut("execution(* com.example..controller..*.*save*(..)) || " +
            "execution(* com.example..controller..*.*delete*(..)) || " +
            "execution(* com.example..controller..*.*update*(..))")
    public void logPointcut(){}

    @SneakyThrows
    @Around("logPointcut()")
    public Object log(ProceedingJoinPoint joinPoint){
        //操作人用户名
        String username = UserContext.getUser();
        //操作人名字

        //操作时间
        LocalDateTime operationTime =LocalDateTime.now();

        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作持续时间
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        long duration = end - begin;

        logMapper.insert(username, operationTime, className, methodName, duration);
        return result;
    }
}
